package com.leesche.zcsp.node.web.service.impl.data.aop.common.log;

import java.util.Date;

import org.apache.log4j.Logger;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

import com.leesche.zcsp.node.web.model.BaseModel;

/**
 * @Title: ServiceLogAspect.java
 * @Package com.leesche.zcsp.node.service.aop
 * @Description:()
 * @author dennies yang
 * @date 2016年9月23日 下午11:08:08
 * @version V1.0
 */

@Aspect
@Component
public class ServiceLogAspect {
	private static final Logger logger = Logger
			.getLogger(ServiceLogAspect.class);


/***
	 *
	 * @Title: serviceAspect
	 * @Description: TODO(定义切点)
	 * @param
	 * @return void
	 * @throws
	 */

	@Pointcut("execution(* com.leesche.zcsp.node.web.service.*.*(..))")
	public void serviceAspect() {
		// System.out.println("我是一个切入点");
	}


/***
	 *
	 * @Title: doBefore @Description: TODO(前置通知执行) @param @param joinPoint @return
	 *         void @throws
	 */

	@Before("serviceAspect()")
	public void doBefore(JoinPoint joinPoint) {
		String methodName = joinPoint.getSignature().getName();
		logger.warn("方法:" + joinPoint.getTarget().getClass().toString() + "."
				+ methodName + "()-------开始执行");
		if (methodName.equals("insert")
				&& joinPoint.getArgs()[0] instanceof BaseModel) {
			((BaseModel) joinPoint.getArgs()[0]).setCreatetime(new Date());
			((BaseModel) joinPoint.getArgs()[0]).setUpdatetime(new Date());
		} else if (methodName.equals("update")
				&& joinPoint.getArgs()[0] instanceof BaseModel) {
			((BaseModel) joinPoint.getArgs()[0]).setUpdatetime(new Date());
		}

	}


/**
	 *
	 * @Title: doAfter @Description: TODO(后置方法执行) @param @param joinPoint @return
	 *         void @throws
	 */

	@AfterReturning(pointcut = "serviceAspect()")
	public void doAfter(JoinPoint joinPoint) {
		logger.warn("方法:" + joinPoint.getTarget().getClass().toString() + "."
				+ joinPoint.getSignature().getName() + "()-------开始结束");
	}


/**
	 *
	 * @Title: doAfter @Description: TODO(抛出异常后开始执行) @param @param joinPoint @param @param
	 *         e @return void @throws
	 */

	@AfterThrowing(value = "serviceAspect()", throwing = "e")
	public void doAfter(JoinPoint joinPoint, Exception e) {
		StringBuilder logInfo = new StringBuilder("方法 :");
		logInfo.append(joinPoint.getTarget().getClass().toString());
		logInfo.append(".");
		logInfo.append(joinPoint.getSignature().getName());
		logInfo.append("()异常信息");
		StackTraceElement[] trace = e.getStackTrace();
		for (StackTraceElement s : trace) {
			logInfo.append("\t ");
			logInfo.append(s);
			logInfo.append("\r\n");

		}

		logger.error(logInfo.toString());
		// handleLog(joinPoint, e);
	}

}
